package com.spx.chapter06;

import com.spx.chapter05.pojo.Event;
import com.spx.util.SampleDataUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;

import java.time.Duration;

/**
 * create by undeRdoG on  2022-05-02  20:10
 * 凡心所向，素履以往，生如逆旅，一苇以航。
 */
public class ReduceFunctionTest {


    public static void main(String[] args) throws Exception {
        /*
         *   需求：返回 10s 内各用户的访问次数
         * */

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        SingleOutputStreamOperator<Event> dataSource = env.fromCollection(SampleDataUtil.getSample())
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.
                                <Event>forBoundedOutOfOrderness(Duration.ZERO)
                                .withTimestampAssigner(new SerializableTimestampAssigner<Event>() {
                                    @Override
                                    public long extractTimestamp(Event element, long recordTimestamp) {
                                        return element.timestamp;
                                    }
                                })
                );

        SingleOutputStreamOperator<Tuple2<String, Long>> mapStream = dataSource.map(new MapFunction<Event, Tuple2<String, Long>>() {
            @Override
            public Tuple2<String, Long> map(Event value) throws Exception {

                return Tuple2.of(value.user, 1L);
            }
        });


        WindowedStream<Tuple2<String, Long>, String, TimeWindow> window = mapStream.keyBy(data -> data.f0)
                // 开一个10s的窗口
                .window(TumblingEventTimeWindows.of(Time.seconds(10L)));


        SingleOutputStreamOperator<Tuple2<String, Long>> reduce = window.reduce(new ReduceFunction<Tuple2<String, Long>>() {
            @Override
            public Tuple2<String, Long> reduce(Tuple2<String, Long> value1, Tuple2<String, Long> value2) throws Exception {

                return Tuple2.of(value1.f0, value1.f1 + value2.f1);

            }
        });

        reduce.print("reduce");

        env.execute();
    }



}
